Skip to main content

push 传参

#定义需要传递的参数

class Arguments {
int id;
String title;
dynamic any;
Arguments(this.id, this.title, this.any);
}



#接受获取传过来的参数

class Me extends StatelessWidget {
static const routeName = '/me';

// @override
// _MeState createState() => _MeState();

Widget build(BuildContext context) {
final Arguments args = ModalRoute.of(context).settings.arguments;
return Text('me' + args.title);
}
}

#把组件注册到路由表中

routes: {
News.routeName: (context) => News(),
App.routeName: (context) => App(),
Me.routeName: (context) => Me(),
},

#点击事件中填写参数

Center(
child: ElevatedButton(
onPressed: () {
// Navigate back to first route when tapped.
Navigator.pushNamed(context, Me.routeName,
arguments: Arguments(2, 'fffffqqqq sd扥f', null));
},
child: Text('Go back!'),
),
);

#方法二
使用 onGenerateRoute 提取参数

修改push
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
Products(item: Arguments(4, 'dfgdf', null))));

接收数据
import 'package:flutter/material.dart';
import '../model/Arguments.dart';

class Products extends StatelessWidget {
static const routeName = '/products';
final Arguments item;

Products({Key key, @required this.item}) : super(key: key);

Widget build(BuildContext context) {
return Text('data' + this.item.id.toString());
}

// @override
// _ProductsState createState() => _ProductsState();
}


使用 onGenerateRoute 提取参数
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
// Provide a function to handle named routes. Use this function to
// identify the named route being pushed, and create the correct
// Screen.
onGenerateRoute: (settings) {
// If you push the PassArguments route
if (settings.name == PassArgumentsScreen.routeName) {
// Cast the arguments to the correct type: ScreenArguments.
final ScreenArguments args = settings.arguments;

// Then, extract the required data from the arguments and
// pass the data to the correct screen.
return MaterialPageRoute(
builder: (context) {
return PassArgumentsScreen(
title: args.title,
message: args.message,
);
},
);
}
// The code only supports PassArgumentsScreen.routeName right now.
// Other values need to be implemented if we add them. The assertion
// here will help remind us of that higher up in the call stack, since
// this assertion would otherwise fire somewhere in the framework.
assert(false, 'Need to implement ${settings.name}');
return null;
},
title: 'Navigation with Arguments',
home: HomeScreen(),
routes: {
ExtractArgumentsScreen.routeName: (context) =>
ExtractArgumentsScreen(),
});
}
}